package com.androideasy.permissions

import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import java.util.ArrayList

class EasyPermissions {
    /**
     * 私有化构造函数
     */
    private constructor(context: Context) {
        mContext = context
        sInterceptor= PermissionInterceptorImpl()
    }

    /** 权限请求拦截器  */
    private var sInterceptor: PermissionInterceptor? = null

    private var sCheckMode: Boolean = false
    /**
     * 是否为检查模式
     */
    fun setCheckMode(checkMode: Boolean) {
        sCheckMode = checkMode
    }

    /**
     * 设置全局权限请求拦截器
     */
    fun setInterceptor(interceptor: PermissionInterceptor?) {
        sInterceptor = interceptor
    }

    /**
     * 获取全局权限请求拦截器
     */
    fun getInterceptor(): PermissionInterceptor? {
        if (sInterceptor == null) {
            sInterceptor = object : PermissionInterceptor {}
        }
        return sInterceptor
    }

    /** Context 对象  */
    private var mContext: Context? = null

    /** 权限列表  */
    private var mPermissions: MutableList<String>? = null

    /** 权限请求拦截器  */
    private var mInterceptor: PermissionInterceptor? = null

    /** 设置不检查  */
    private var mCheckMode: Boolean? = null


    fun permission(permissions: List<String>): EasyPermissions? {
        if (permissions == null || permissions.isEmpty()) {
            return this
        }
        if (mPermissions == null) {
            mPermissions = ArrayList(permissions)
            return this
        }
        for (permission in permissions) {
            if (mPermissions!!.contains(permission)) {
                continue
            }
            mPermissions!!.add(permission)
        }
        return this
    }

    /**
     * 设置权限请求拦截器
     */
    fun interceptor(interceptor: PermissionInterceptor?): EasyPermissions {
        mInterceptor = interceptor
        return this
    }

    /**
     * 设置不触发错误检测机制
     */
    fun unchecked(): EasyPermissions? {
        mCheckMode = false
        return this
    }

    /**
     * 请求权限
     */
    fun request(callback: PermissionCallback ) {
        if (mContext == null) {
            return
        }
        if (mInterceptor == null) {
            mInterceptor = getInterceptor()
        }

        // 权限请求列表（为什么直接不用字段？因为框架要兼容新旧权限，在低版本下会自动添加旧权限申请）
        val permissions: List<String>? = mPermissions //MutableList(mPermissions!!)
        if (mCheckMode == null) {
            if (sCheckMode == null) {
                sCheckMode = PermissionUtils.isDebugMode(mContext!!)
            }
            mCheckMode = sCheckMode
        }

        // 检查当前 Activity 状态是否是正常的，如果不是则不请求权限
        val activity = PermissionUtils.findActivity(mContext)!!
        if (!PermissionUtils.checkActivityStatus(activity, mCheckMode!!)) {
            return
        }

        // 必须要传入正常的权限或者权限组才能申请权限
        if (!PermissionUtils.checkPermissionArgument(permissions, mCheckMode!!)) {
            return
        }
        if (mCheckMode!!) {
            // 检查申请的存储权限是否符合规范
            PermissionUtils.checkStoragePermission(mContext!!, permissions!!)
            // 检查申请的定位权限是否符合规范
            PermissionUtils.checkLocationPermission(mContext!!, permissions!!)
            // 检查申请的权限和 targetSdk 版本是否能吻合
            PermissionUtils.checkTargetSdkVersion(mContext!!, permissions!!)
        }
        if (mCheckMode!!) {
            // 检测权限有没有在清单文件中注册
            PermissionUtils.checkManifestPermissions(mContext!!, permissions!!)
        }

        // 优化所申请的权限列表
        PermissionUtils.optimizeDeprecatedPermission(permissions!!.toMutableList())
        if (PermissionUtils.isGrantedPermissions(mContext!!, permissions!!)) {
            // 证明这些权限已经全部授予过，直接回调成功
            if (callback != null) {
                mInterceptor!!.grantedPermissions(
                    activity,
                    permissions,
                    permissions,
                    true,
                    callback
                )
            }
            return
        }

        // 申请没有授予过的权限
        mInterceptor!!.requestPermissions(activity!!, callback!!, permissions)
    }
    /**
     * 添加权限组
     */
//    fun permission(vararg permissions: String): EasyPermissions {
//        return permission(permissions.asList())!!
//    }
     fun permission(  permissions: String): EasyPermissions {
        var s = mutableListOf<String>()
        s.add(permissions)
        return permission(s)!!
    }
    fun permission( permissions: Array<String>): EasyPermissions {
        return permission(permissions.asList())!!
    }

    companion object {
        /** 权限设置页跳转请求码  */
        val REQUEST_CODE = 0xFF01


        fun with(context: Context): EasyPermissions {
            return EasyPermissions(context)
        }

        fun with(fragment: Fragment): EasyPermissions? {
            return with(fragment.activity as FragmentActivity)
        }




//    fun permission(vararg permissions: Array<String>): EasyPermissions {
//        return permission(permissions)
//    }



        /**
         * 判断一个或多个权限是否全部授予了
         */
        fun isGranted(context: Context, vararg permissions: String): Boolean {
            return isGranted(context, permissions.asList())
        }

//    fun isGranted(context: Context, vararg permissions: List<String>): Boolean {
//        return isGranted(context, permissions.asList())
//    }

        fun isGranted(context: Context, permissions: List<String>): Boolean {
            return PermissionUtils.isGrantedPermissions(context!!, permissions)
        }

        /**
         * 获取没有授予的权限
         */
        fun getDenied(context: Context, vararg permissions: String): List<String> {
            return getDenied(context, permissions.asList())
        }

//    fun getDenied(context: Context,   permissions: Array<String>): List<String> {
//        return getDenied(context, permissions.asList())//PermissionUtils.asArrayLists(permissions)
//    }

        fun getDenied(context: Context, permissions: List<String>): List<String> {
            return PermissionUtils.getDeniedPermissions(context, permissions)
        }

        /**
         * 判断某个权限是否为特殊权限
         */
        fun isSpecial(permission: String?): Boolean {
            return PermissionUtils.isSpecialPermission(permission!!)
        }

        /**
         * 判断一个或多个权限是否被永久拒绝了
         *
         * （注意不能在请求权限之前调用，应该在 [PermissionCallback.onDenied] 方法中调用）
         */
        fun isPermanentDenied(activity: FragmentActivity, vararg permissions: String): Boolean {
            return isPermanentDenied(activity, permissions.asList())
        }

//    fun isPermanentDenied(  activity: FragmentActivity,  vararg permissions: Array<String>   ): Boolean {
//        return isPermanentDenied(activity, permissions.asList())
//    }

        fun isPermanentDenied(activity: FragmentActivity, permissions: List<String>): Boolean {
            return PermissionUtils.isPermissionPermanentDenied(activity, permissions)
        }

        fun startPermissionActivity(context: Context) {
            startPermissionActivity(context, null as List<String>)
        }

        fun startPermissionActivity(context: Context, vararg permissions: String) {
            startPermissionActivity(context, permissions.asList())
        }

//    fun startPermissionActivity(context: Context, vararg permissions: Array<String>) {
//        startPermissionActivity(context, PermissionUtils.asArrayLists(permissions))
//    }

        /**
         * 跳转到应用权限设置页
         *
         * @param permissions           没有授予或者被拒绝的权限组
         */
        fun startPermissionActivity(context: Context, permissions: List<String>) {
            val activity = PermissionUtils.findActivity(context)
            if (activity != null) {
                startPermissionActivity(activity, permissions)
                return
            }
            val intent = PermissionSettingPage.getSmartPermissionIntent(context, permissions)
            if (context !is FragmentActivity) {
                intent!!.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }

        /* android.app.Activity */

        /* android.app.Activity */
        fun startPermissionActivity(activity: FragmentActivity) {
            startPermissionActivity(activity, null as List<String>)
        }

        fun startPermissionActivity(activity: FragmentActivity, vararg permissions: String) {
            startPermissionActivity(activity, permissions.asList())
        }

//    fun startPermissionActivity(activity: FragmentActivity, vararg permissions: Array<String>) {
//        startPermissionActivity(activity, PermissionUtils.asArrayLists(permissions))
//    }

        fun startPermissionActivity(activity: FragmentActivity, permissions: List<String>) {
            startPermissionActivity(activity, permissions, REQUEST_CODE)
        }

        /**
         * 跳转到应用权限设置页
         *
         * @param permissions           没有授予或者被拒绝的权限组
         * @param requestCode           Activity 跳转请求码
         */
        fun startPermissionActivity(
            activity: FragmentActivity,
            permissions: List<String>,
            requestCode: Int
        ) {
            activity.startActivityForResult(
                PermissionSettingPage.getSmartPermissionIntent(
                    activity,
                    permissions
                ), requestCode
            )
        }

        fun startPermissionActivity(fragment: Fragment) {
            startPermissionActivity(fragment, null as List<String>)
        }

        fun startPermissionActivity(fragment: Fragment, vararg permissions: String) {
            startPermissionActivity(fragment, permissions.asList())
        }

//    fun startPermissionActivity(fragment: Fragment, vararg permissions: Array<String>) {
//        startPermissionActivity(fragment, permissions.asList())
//    }

        fun startPermissionActivity(fragment: Fragment, permissions: List<String>) {
            startPermissionActivity(fragment, permissions, REQUEST_CODE)
        }

        /**
         * 跳转到应用权限设置页
         *
         * @param permissions           没有授予或者被拒绝的权限组
         * @param requestCode           Activity 跳转请求码
         */
        fun startPermissionActivity(
            fragment: Fragment,
            permissions: List<String>,
            requestCode: Int
        ) {
            val activity = fragment.activity ?: return
            fragment.startActivityForResult(
                PermissionSettingPage.getSmartPermissionIntent(
                    activity,
                    permissions
                ), requestCode
            )
        }
    }
}